import pyperclip
from typing import List, Tuple


class PairSorter:
    """将每 n 行为一组的文本按第一行长度排序"""

    def __init__(self, group_size: int = 2):
        """
        group_size: 每组行数
        """
        if group_size <= 0:
            raise ValueError("group_size 必须大于0")
        self.group_size = group_size

    @staticmethod
    def read_input() -> List[str]:
        """从控制台读取多行文本，空行结束"""
        print(f"请输入内容（每 {2} 行为一个单元，输入空行结束）：")
        lines = []
        while True:
            line = input()
            if line == "":
                break
            lines.append(line)
        return lines

    def group_lines(self, lines: List[str]) -> List[Tuple[str, ...]]:
        """将文本按 group_size 分组"""
        # 如果最后一组不足 group_size，则忽略
        total_full_groups = len(lines) // self.group_size
        lines = lines[:total_full_groups * self.group_size]
        groups = [tuple(lines[i:i+self.group_size]) for i in range(0, len(lines), self.group_size)]
        return groups

    def sort_groups(self, groups: List[Tuple[str, ...]]) -> List[Tuple[str, ...]]:
        """按每组的第一行长度排序"""
        return sorted(groups, key=lambda x: len(x[0]))

    def process_and_copy(self, lines: List[str]) -> str:
        """处理文本并复制到剪贴板"""
        groups = self.group_lines(lines)
        sorted_groups = self.sort_groups(groups)
        result = '\n'.join(['\n'.join(group) for group in sorted_groups])

        return result


if __name__ == "__main__":
    sorter = PairSorter(group_size=2)
    lines = sorter.read_input()
    final_text = sorter.process_and_copy(lines)

    print("\n排序后的结果：\n")
    print(final_text)
    print("\n✅ 已复制到剪贴板！")
